package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据id判断当前用户是否关注了他
     *
     * @param id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        return Result.ok(count > 0);
    }

    /**
     * 关注逻辑
     * 如果是关注，向关注表插入一条关注记录，再向当前用户redis中的关注SET加入该用户id
     * 如果是取消，删除关注记录，再向当前用户redis中的关注SET删除该用户id
     *
     * @param id
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long id, Boolean isFollow) {
        // 关注还是取关
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        // 关注
        if (isFollow) {
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean save = save(follow);
            if (save) {
                // 保存成功 写入redis
                stringRedisTemplate.opsForSet().add(key, id.toString());
            }
        } else {
            boolean remove =
                    remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", id));
            if (remove) {
                stringRedisTemplate.opsForSet().remove(key, id.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 显示共同好友
     * 由于每个用户都有对应的关注列表SET，对其取交集即可
     *
     * @param id
     * @return
     */
    @Override
    public Result common(Long id) {
        // 要求共同关注好友：交集 基于set集合  sinter s1 s2
        // 前提改造接口 每次关注他人，存入redis k:当前用户id，v:关注列表
        Long userId = UserHolder.getUser().getId();
        String myKey = "follows:" + userId;
        String otherKey = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(myKey, otherKey);

        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> interSet = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(interSet);
        List<UserDTO> userDtoList = users
                .stream()
                .map(u -> BeanUtil.copyProperties(u, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDtoList);
    }
}
